<template>
  <div class="login_container">
    <div class="connect">
      <div class="login_left">
        <img class="school_logo" src="@/assets/images/loginx.png" alt="" />
      </div>
      <div class="login_right">
        <div class="login_right_top">
          <div class="flex">
            <img
              class="user_login_icon"
              src="@/assets/images/formlogo.png"
              alt=""
            />
            <div class="login_title">教学管理平台</div>
          </div>
        </div>
        <el-tabs v-if="!isReset" v-model="activeName" style="margin-top: 20px">
          <el-tab-pane label="密码登录" name="password">
            <el-form
              ref="loginForm"
              class="loginForm"
              :model="loginForm"
              :rules="loginRules"
            >
              <el-form-item prop="username">
                <el-input
                  v-input-restrict
                  class="form_ipt"
                  v-model="loginForm.username"
                  type="text"
                  auto-complete="off"
                  placeholder="请输入账号"
                >
                  <img
                    slot="prefix"
                    class="ipt_icon"
                    src="../assets/images/ipt_user_icon.png"
                    alt=""
                  />
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-input-restrict
                  class="form_ipt"
                  v-model="loginForm.password"
                  type="password"
                  auto-complete="off"
                  placeholder="请输入密码"
                  @keyup.enter.native="handleLogin"
                  show-password
                >
                  <img
                    slot="prefix"
                    class="ipt_pwd_icon"
                    src="../assets/images/ipt_pwd_icon.png"
                    alt=""
                  />
                </el-input>
              </el-form-item>
              <el-form-item>
                <div class="tipline">
                  <el-checkbox v-model="loginForm.rememberMe" class="remember"
                    >记住密码</el-checkbox
                  >
                  <div class="forget" @click="isReset = true">忘记密码？</div>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button
                  class="login_btn"
                  :loading="loading"
                  size="medium"
                  type="primary"
                  @click.native.prevent="handleLogin"
                >
                  <span class="font_bold" v-if="!loading">登 录</span>
                  <span class="font_bold" v-else>登 录 中...</span>
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="验证码登录" name="phone">
            <el-form
              ref="phoneLoginForm"
              class="loginForm"
              :model="phoneLoginForm"
              :rules="phoneLoginRules"
            >
              <el-form-item prop="phoneNumber">
                <el-input
                  v-input-restrict
                  class="form_ipt"
                  v-model="phoneLoginForm.phoneNumber"
                  type="text"
                  auto-complete="off"
                  placeholder="请输入手机号"
                >
                  <img
                    slot="prefix"
                    class="phoneNumber_icon"
                    src="../assets/images/phoneNumber_icon.png"
                    alt=""
                  />
                </el-input>
              </el-form-item>
              <el-form-item prop="phoneCode">
                <el-input
                  v-input-restrict
                  oninput="value=value.replace(/^-1|[^0-9]/g,'')"
                  maxlength="6"
                  class="form_ipt"
                  v-model="phoneLoginForm.phoneCode"
                  type="text"
                  auto-complete="off"
                  placeholder="请输入验证码"
                  @keyup.enter.native="handlePhoneLogin"
                >
                  <img
                    slot="prefix"
                    class="code_icon"
                    src="../assets/images/code_icon.png"
                    alt=""
                  />
                  <div
                    class="get_code"
                    slot="suffix"
                    @click="getVerCode"
                    v-if="ifSend"
                  >
                    {{ ifFistClick ? "获取验证码" : "重新获取" }}
                  </div>
                  <div class="get_code" slot="suffix" v-else>{{ second }}S</div>
                </el-input>
              </el-form-item>
              <el-form-item>
                <div class="tipline">
                  <div @click="activeName = 'password'" class="forget">
                    返回密码登录
                  </div>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button
                  class="login_btn"
                  :loading="loading"
                  size="medium"
                  type="primary"
                  @click.native.prevent="handlePhoneLogin"
                >
                  <span class="font_bold" v-if="!loading">确 认</span>
                  <span class="font_bold" v-else>确 认 中...</span>
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <el-tabs v-else v-model="resetactiveName" style="margin-top: 20px">
          <el-tab-pane label="重置密码" name="resetactiveName">
            <el-form
              ref="phoneLoginForm"
              class="loginForm"
              :model="phoneLoginForm"
              :rules="phoneLoginRules"
            >
              <el-form-item prop="phoneNumber">
                <el-input
                  v-input-restrict
                  class="form_ipt"
                  v-model="phoneLoginForm.phoneNumber"
                  type="text"
                  auto-complete="off"
                  placeholder="请输入手机号"
                >
                  <img
                    slot="prefix"
                    class="phoneNumber_icon"
                    src="../assets/images/phoneNumber_icon.png"
                    alt=""
                  />
                </el-input>
              </el-form-item>
              <el-form-item prop="phoneCode">
                <el-input
                  v-input-restrict
                  oninput="value=value.replace(/^-1|[^0-9]/g,'')"
                  maxlength="6"
                  class="form_ipt"
                  v-model="phoneLoginForm.phoneCode"
                  type="text"
                  auto-complete="off"
                  placeholder="请输入验证码"
                  @keyup.enter.native="handlePhoneLogin"
                >
                  <img
                    slot="prefix"
                    class="code_icon"
                    src="../assets/images/code_icon.png"
                    alt=""
                  />
                  <div
                    class="get_code"
                    slot="suffix"
                    @click="getVerCode"
                    v-if="ifSend"
                  >
                    {{ ifFistClick ? "获取验证码" : "重新获取" }}
                  </div>
                  <div class="get_code" slot="suffix" v-else>{{ second }}S</div>
                </el-input>
              </el-form-item>
              <el-form-item prop="newPassword">
                <el-input
                  v-input-restrict
                  class="form_ipt"
                  v-model="phoneLoginForm.newPassword"
                  type="password"
                  show-password
                  auto-complete="off"
                  placeholder="设置密码:6-16位字母和数字"
                >
                  <img
                    slot="prefix"
                    class="ipt_pwd_icon"
                    src="../assets/images/ipt_pwd_icon.png"
                    alt=""
                  />
                </el-input>
                <div
                  class="abso"
                  @click="isReset = false"
                  style="
                    right: 0;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #1ab394;
                    cursor: pointer;
                  "
                >
                  去登录
                </div>
              </el-form-item>
              <el-form-item>
                <el-button
                  class="login_btn"
                  :loading="loading"
                  size="medium"
                  type="primary"
                  @click.native.prevent="handlePhoneLogin"
                >
                  <span class="font_bold" v-if="!loading">确 认</span>
                  <span class="font_bold" v-else>确 认 中...</span>
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- <div class="icp_content">
      <span
        @click="turnTo('https://beian.miit.gov.cn/#/Integrated/recordQuery')"
        >杭钢炽橙智能科技有限公司 备案号：浙ICP备18057432号-3</span
      >
    </div> -->
    <div class="suggest_content">
      <span @click="turnTo('https://www.google.cn/chrome/next-steps.html')"
        >推荐使用Chrome浏览器</span
      >
    </div>
  </div>
</template>

<script>
import {
  getCodeImg,
  sendPhoneCode,
  loginV2,
  getPhoneLoginEnabled,
} from "@/api/login";
import { updatePwd } from "@/api/system/user";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { checkPhone, checkPassword } from "@/utils/validate";
export default {
  name: "Login",
  components: {},
  data() {
    return {
      isReset: false,
      resetactiveName: "resetactiveName",
      activeName: "password",
      bgImg: `${process.env.VUE_APP_BASE_OSSALI}bg_login_img.jpg`,
      logoImg: `${process.env.VUE_APP_BASE_OSSALI}school_logo.png`,
      routePath: {
        1: `${process.env.VUE_APP_BASE_WWW}/teacher/login`,
        2: `${process.env.VUE_APP_BASE_WWW}/student/login`,
        3: `${process.env.VUE_APP_BASE_WWW}/login`,
      },
      loginType: 3,
      options: [
        {
          value: 1,
          label: "我是教师",
        },
        {
          value: 2,
          label: "我是学生",
        },
        {
          value: 3,
          label: "我是管理员",
        },
      ],
      pageTitle: "用户登录",
      forgetForm: {},
      activeIndex: "0",
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      ifSend: true,
      ifFistClick: true,
      second: "",
      needPhone: false,
      phoneLoginEnabled: false,
      phoneLoginForm: {
        phoneNumber: "",
        phoneCode: "",
        newPassword: "",
      },
      phoneLoginRules: {
        phoneNumber: [
          { required: true, trigger: "blur", validator: checkPhone() },
        ],
        phoneCode: [
          { required: true, trigger: "blur", message: "请输入验证码" },
        ],
        newPassword: [
          { required: true, trigger: "blur", validator: checkPassword },
        ],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      forgetPassword: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    // this.getCode();
    this.getPhoneLoginEnabled();
    this.getCookie();
  },
  methods: {
    async getPhoneLoginEnabled() {
      let res = await getPhoneLoginEnabled();
      const { code } = res;
      if (code == 200) {
        this.phoneLoginEnabled = res.phoneLoginEnabled;
      }
    },
    async getVerCode() {
      if (!this.ifSend) {
        return;
      }
      if (!this.phoneLoginForm.phoneNumber) {
        this.$message("请输入手机号");
        return;
      }
      let params = {
        phone: this.phoneLoginForm.phoneNumber,
      };
      let res = await sendPhoneCode(params);
      this.ifFistClick = false;
      this.second = 59;
      this.ifSend = false;
      let time = null;
      clearInterval(time);
      time = setInterval(() => {
        if (this.second > 0) {
          this.second--;
        } else {
          clearInterval(time);
          this.ifSend = true;
        }
      }, 1000);
    },
    turnTo(url) {
      window.open(url);
    },
    routeTo(type) {
      window.location.replace(this.routePath[type]);
    },
    showForgetPassword() {
      this.forgetPassword = true;
      this.pageTitle = "找回密码";
    },
    showLogin() {
      this.forgetPassword = false;
      this.pageTitle = "用户登录";
    },
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.loginForm.port = 0;
          //phoneLoginEnabled  是否需要手机号验证码登录
          if (this.phoneLoginEnabled) {
            loginV2(this.loginForm)
              .then((res) => {
                //如果时admin等超级管理员角色  不需要手机号验证直接给token登录
                if (res.token) {
                  this.$store
                    .dispatch("setV2Token", res.token)
                    .then(() => {
                      this.needPhone = false;
                      this.$router
                        .push({ path: this.redirect || "/" })
                        .catch(() => {});
                    })
                    .catch(() => {
                      this.loading = false;
                      if (this.captchaEnabled) {
                        this.getCode();
                      }
                    });
                } else {
                  this.needPhone = true;
                  this.loading = false;
                  this.phoneLoginForm.phoneNumber = res.phone;
                }
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            this.$store
              .dispatch("Login", this.loginForm)
              .then(() => {
                this.needPhone = false;
                this.$router
                  .push({ path: this.redirect || "/" })
                  .catch(() => {});
              })
              .catch(() => {
                this.loading = false;
                if (this.captchaEnabled) {
                  this.getCode();
                }
              });
          }
        }
      });
    },
    handlePhoneLogin() {
      this.$refs.phoneLoginForm.validate((valid) => {
        if (valid) {
          if (!this.isReset) {
            this.loading = true;
            let params = {
              port: 0,
              phone: this.phoneLoginForm.phoneNumber,
              phoneCode: this.phoneLoginForm.phoneCode,
              // password: this.loginForm.password,
            };
            this.$store
              .dispatch("phoneLogin", params)
              .then(() => {
                this.$router
                  .push({ path: this.redirect || "/" })
                  .catch(() => {});
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            this.loading = true;
            updatePwd({
              phoneNumber: this.phoneLoginForm.phoneNumber,
              phoneCode: this.phoneLoginForm.phoneCode,
              newPassword: this.phoneLoginForm.newPassword,
            })
              .then((response) => {
                this.$modal.msgSuccess("修改密码成功，快去登录吧!");
                this.loading = false;
                this.isReset = false;
                this.activeName = "password";
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" scoped lang="scss">
::v-deep .el-input__suffix {
  height: 52px;
  margin-right: 5px;
}
.login_container {
  // 设置背景
  background: url("../assets/images/loginbg.jpg");
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  ::v-deep .el-tabs__item.is-active {
    color: #9a8057;
  }
  ::v-deep .el-tabs__item:hover {
    color: #9a8057;
  }
  ::v-deep .el-tabs__active-bar {
    background-color: #9a8057;
  }
  ::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #9a8057;
  }
  ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner,
  .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    background-color: #9a8057;
    border-color: #9a8057;
  }
}
.connect {
  display: flex;
  align-items: center;
  .login_left {
    .school_logo {
      width: 618px;
      height: auto;
    }
  }
  .login_right {
    margin-left: 20px;
    width: 512px;
    height: 520px;
    box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.14);
    border-radius: 20px 20px 20px 20px;
    background: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    ::v-deep .form_ipt.el-input--medium .el-input__inner {
      width: 360px;
      height: 48px;
      background: #ffffff;
      border-radius: 30px;
      line-height: 48px;
      padding-left: 62px;
      box-sizing: border-box;
    }
    ::v-deep .el-input__prefix {
      margin-top: 11px;
      left: 32px;
    }
    .login_btn {
      margin-top: 23px;
      width: 360px !important;
      height: 48px;
      background: #9a8057;
      border-radius: 30px;
      border-color: #9a8057;
    }
  }
}
.icp_content {
  width: 100%;
  display: flex;
  justify-content: center;
  position: fixed;
  bottom: 30px;
  left: 0;
  color: #a4a4a4;
  font-size: 16px;
  font-weight: 500;
  span {
    cursor: pointer;
  }
}
.suggest_content {
  width: 100%;
  display: flex;
  justify-content: center;
  position: fixed;
  bottom: 10px;
  left: 0;
  color: #2191df;
  font-size: 16px;
  font-weight: 500;
  span {
    cursor: pointer;
  }
}
.login_right_top {
  width: 100%;
  display: flex;
  border-bottom: 1px solid #f5f5f6;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
  .user_login_icon {
    width: 268px;
    height: 57px;
  }
  .login_title {
    line-height: 57px;
    margin-left: 15px;
    font-size: 24px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 500;
    color: #333333;
  }
  .right_title {
    width: 120px;
    position: relative;
  }
  .down_select {
    width: 20px;
    height: 20px;
    position: absolute;
    top: 8px;
    right: 0;
  }
}
.loginForm {
  margin-top: 10px;
}
.tipline {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 10px 0 32px;
  box-sizing: border-box;
  .remember {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
  }
  .forget {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    cursor: pointer;
    user-select: none;
  }
}
.shou {
  cursor: pointer;
  align-items: center;
  user-select: none;
}
::v-deep .right_title .el-input--medium .el-input__inner {
  border: 0;
  text-align: right;
  font-size: 18px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #28b28b;
  line-height: 25px;
  background: transparent;
  padding: 0 26px 0 0;
}
::v-deep .el-icon-arrow-up:before {
  display: none;
}
.font_bold {
  font-size: 18px;
  font-weight: bold;
}
.ipt_icon {
  width: 19px;
  height: 20px;
}
.phoneNumber_icon {
  width: 14px;
  height: 20px;
}
.code_icon {
  width: 18px;
  height: 20px;
}
.ipt_pwd_icon {
  width: 16px;
  height: 20px;
}
.get_code {
  cursor: pointer;
  user-select: none;
  color: #9A8057;
  margin: 6px 16px 0 0;
}
</style>
